package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.qq.connect.AccessToken;
import com.qq.connect.InfoToken;
import com.qq.util.ParseString;
import com.qq.util.Verify;
import com.qq.util.XMLHelper;

public class CallbackServlet extends HttpServlet {

    private static final long serialVersionUID = -2322076209328057187L;
    private String oauth_token;
    private String openid;
    private String oauth_signature;
    private String oauth_vericode;
    private String timestamp;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        oauth_token = request.getParameter("oauth_token");
        openid = request.getParameter("openid");
        oauth_signature = request.getParameter("oauth_signature");
        oauth_vericode = request.getParameter("oauth_vericode");
        timestamp = request.getParameter("timestamp");

        PrintWriter out = response.getWriter();

        /**
         * QQ互联登录，授权成功后会回调此地址 必须要用授权的request token换取access token
         * 访问QQ互联的任何资源都需要access token 目前access token是长期有效的，除非用户解除与第三方绑定
         * 如果第三方发现access token失效，请引导用户重新登录QQ互联，授权，获取access token
         */
        // http://homepage.sosolabs.com/call?oauth_token=14162898880223603901&openid=F08332A45A14FEC1CFFA452E4E6FCACE&oauth_signature=9wEyosuYRa52LMOjrkuIfMgu%2FKY%3D&oauth_vericode=786730574&timestamp=1305018289
        // 授权成功后，会返回用户的openid
        // 检查返回的openid是否是合法id
        try {
            if (!Verify.verifyOpenID(openid, timestamp, oauth_signature)) {
                out.println("openid verify false!");
            }
        } catch (InvalidKeyException e1) {
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }

        // tips
        // 这里已经获取到了openid，可以处理第三方账户与openid的绑定逻辑
        // 但是我们建议第三方等到获取accesstoken之后在做绑定逻辑

        // 用授权的request token换取access token
        AccessToken token = new AccessToken();
        String oauth_token_secret = (String) request.getSession().getAttribute("oauth_token_secret");
        // out.println(oauth_token_secret);
        // out.println(oauth_vericode);
        String access_token = null;
        try {
            access_token = token.getAccessToken(oauth_token, oauth_token_secret, oauth_vericode);
        } catch (InvalidKeyException e1) {
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }
        // System.out.println(access_token);
        HashMap<String, String> tokens = ParseString.parseTokenString(access_token);

        // error
        if (tokens.get("error_code") != null) {
            out.println(tokens.get("error_code"));
        }

        // 获取access token成功后也会返回用户的openid
        // 我们强烈建议第三方使用此openid
        // 检查返回的openid是否是合法id
        try {
            if (!Verify.verifyOpenID(tokens.get("openid"), tokens.get("timestamp"), tokens.get("oauth_signature"))) {
                out.println("openid verify false2!");
            }
        } catch (InvalidKeyException e1) {
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }
        // 将access token，openid保存!!
        oauth_token = tokens.get("oauth_token");
        oauth_token_secret = tokens.get("oauth_token_secret");
        openid = tokens.get("openid");

        InfoToken infotoken = new InfoToken();
        String info_xml = null;
        try {
            info_xml = infotoken.getInfo(oauth_token, oauth_token_secret, openid, "xml");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // out.println(userinfo_xml);
        HashMap<String, String> userinfo = null;
        try {
            userinfo = XMLHelper.getInstance().getInfo(info_xml);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        // 第三方处理用户绑定逻辑
        // 将openid与第三方的帐号做关联
        // bind_to_openid();
        request.getSession().setAttribute("islogin", 1);
        request.getSession().setAttribute("openid", openid);
        request.getSession().setAttribute("nickname", new String(userinfo.get("nickname").getBytes("ISO-8859-1"), "UTF-8"));
        request.getSession().setAttribute("figureurl", userinfo.get("figureurl"));
        request.getSession().setAttribute("oauth_token", oauth_token);
        request.getSession().setAttribute("oauth_token_secret", oauth_token_secret);

        response.sendRedirect("../../");
    }

}
